package com.gexin.common.utils;
import java.util.HashMap;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.gexin.common.AppGlobal;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.cache.RedisKeyConst;
import com.gexin.common.model.ApiResponse;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
/**
 * 发送短信接口工具类
 * @author 肖得明
 *
 */
public class MessageUtils {
	public static final String ADUIT_SUCCESS_ID = "494144";
	public static final String ADUIT_FAIL_ID = "494145";
	private static Log log = Log.getLog(MessageUtils.class);
	//===================================================
	private final static  String accountSid = StringUtil.getBundelPath ("config","main_account");// 主账户Id
	private final static  String authToken =StringUtil.getBundelPath ("config","main_token") ;// 主账户授权令牌
	private final static  String appId = StringUtil.getBundelPath ("config","app_id") ;// 应用Id
	private  final  static Integer  Max_send_msg_size = AppGlobal.dev_Mode==true?115:10;
	//=========================
	public static String loginId="485478";//发送验证码的模板  【格欣信息】您的验证码为：xxxxx,请在十分钟内正确输入。
    public static void main(String[] args) {
		PropKit.use("config.properties");
		System.err.println(MessageUtils.sendTemplateSMS("18616372930", MessageUtils.loginId, new String[]{"599688","十分钟"}));
	}
    
	public static String getRealIpV2(HttpServletRequest request) {
		String accessIP = request.getHeader("x-forwarded-for");
		if (null == accessIP)
			return request.getRemoteAddr();
		return accessIP;
	}
    
	
	public static boolean verify(String token,String code){
		if (StringUtil.isEmpty(token) || StringUtil.isEmpty(code)) {
			return false;
		}
		Object result = CacheUtils.get(token);
		if (result==null) {
			return false;
		}
		//验证码验证一次之后立即失效
		CacheUtils.del(token);
		if ((result.toString()).equals(code)) {
			return true;
		}else {
			return false;
		}
	}
	
	/**
     * 发送短信验证码
     * @param phone  手机号码
     * @param code  发送的验证码
     * @param moid   模板的ID
     * @param session  httpsession
     * @return  
     */
    public static ApiResponse SendCode_New(String phone,String code , String moid,HttpServletRequest  req){
    	String key = RedisKeyConst.Message_Send+phone;
    	ApiResponse cmd =null;
    	Integer size = CacheUtils.get("time:"+key);
    	if(size==null){
    		 CacheUtils.set("time:"+key,1,RedisKeyConst.day);
    		 size =  CacheUtils.get("time:"+key);
    	}else{
    		if(size>=Max_send_msg_size){

    			log.error(String.format("短信发送异常：号码:%s,请求发送次数:%s次，Ip:%s", phone,size,getRealIpV2(req)));
    			size++;
        		CacheUtils.set("time:"+key,size,RedisKeyConst.day);
    			return  new ApiResponse(false,"验证码一天最多10次");
    		}
    	}
		if(CacheUtils.exists(key)==true){
			cmd = new ApiResponse(false, "发送时间太短了！");
			return cmd ;
		}
		if(StringUtil.isEmpty(phone)==false){
			CacheUtils.set(key, phone, RedisKeyConst.Message_Send_time);
			//如果是测试模式 ====================================
			if(AppGlobal.dev_Mode){
				CacheUtils.set(RedisKeyConst.Message_Code+moid+phone, "0000", RedisKeyConst.Message_Code_time);
				log.info("测试模式发送验证码:================="+phone+"验证码为:0000");
				cmd = new ApiResponse(true, "发送成功！");
				return cmd;
			}

			if (phone.equals("15050050010")){
				CacheUtils.set(RedisKeyConst.Message_Code+moid+phone, "0000", RedisKeyConst.Message_Code_time);
				log.info("测试账号发送验证码:================="+phone+"验证码为:0000");
				cmd = new ApiResponse(true, "发送成功！");
				return cmd;
			}

			if(sendTemplateSMS(phone, moid, code)==true){
				size++;
	    		CacheUtils.set("time:"+key,size,RedisKeyConst.day);
				//把验证码存到redis 里面去
				CacheUtils.set(RedisKeyConst.Message_Code+moid+phone, code, RedisKeyConst.Message_Code_time);
				log.info("发送验证码为："+phone+":"+code);
				cmd = new ApiResponse(true, "发送成功！");
			}else{
				cmd = new ApiResponse(true, "发送失败请稍后再试！");
			}
		}else{
			cmd =(new ApiResponse(false, "参数错误！"));
		}
		return cmd ;
    }
    
    /**
     * 监测验证码是否正确
     * @param phone    手机号码
     * @param code   验证码
     * @param moid  模板的编号
     * @return
     */
    public static boolean  CheckCode(String phone,String code,String moid){
    	String perincode = CacheUtils.get(RedisKeyConst.Message_Code+moid+phone);
    	if(perincode!=null && code.equals(perincode)){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    public static void  delCode(String phone,String moid){
    	CacheUtils.del(RedisKeyConst.Message_Code+moid+phone);
    }
	//18521532188  18606160344
	/**
	 * 发送短信
	 * @param phone 发送的手机号码
	 * @param mbid  
	 * @return
	 */
	public static String SendPhoneCode(String phone,String mbid){
		Random rand = new Random(); 
		String code = StringUtil.fillString(rand.nextInt(10000)+"", "0", 4, StringUtil.FILL_TYPE_LEFT);
		if(sendTemplateSMS(phone,mbid,code)==true){
			return code;
		}else{
			return null;
		}
	}
	
	
	/**
	 * 发送的模板的消息
	 * @param to  要发送的手机号码
	 * @param templateId  模板的ID
	 * @param datas  发送的数据
	 * @return
	 */
	public static Boolean sendTemplateSMS(String to,String templateId, String[] datas){
		CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		restAPI.init("app.cloopen.com", "8883");
		restAPI.setAccount(accountSid, authToken);
		restAPI.setAppId(appId);
		HashMap<String, Object> result = null;
		result = restAPI.sendTemplateSMS(to,templateId,datas);
		if("000000".equals(result.get("statusCode"))){
		 /*//正常返回输出data包体信息（map）
			HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
			Set<String> keySet = data.keySet();
			for(String key:keySet){
				Object object = data.get(key);
				System.out.println(key +" = "+object);
			}*/
			return true;
		}else{
			//异常返回输出错误码和错误信息
			log.info("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			return false;

		}
	
	}
	
	
	/**
	 * 发送的模板的消息
	 * @param to  要发送的手机号码
	 * @param templateId  模板的ID
	 * @param datas  发送的数据
	 * @return
	 */
	public static Boolean sendTemplateSMS(String to,String templateId, String datas){
	   //测试关闭发短信的接口
	   CCPRestSmsSDK restAPI = new CCPRestSmsSDK();
		restAPI.init("app.cloopen.com", "8883");
		restAPI.setAccount(accountSid, authToken);
		restAPI.setAppId(appId);
		HashMap<String, Object> result = null;
		result = restAPI.sendTemplateSMS(to,templateId,new String[]{datas,"十分钟"});
		if("000000".equals(result.get("statusCode"))){
			return true;
		}else{
			//异常返回输出错误码和错误信息
			log.error("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
			return false;
		}

	}
	
	
	
}
